﻿using Games.Common;
using Games.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Games.Box
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    partial class BoxPage : ContentPage
    {
        IDataBase database = DependencyService.Get<IDataBase>();
        Game game;
        GameInfo gameInfo;
        int xMargin = 0;
        int yMargin = 0;
        int cellSize;
        int layoutWidth, layoutHeight;
        Data map = new Data();
        BoxLevel boxLevel;
        int index0 = 0;
        ScrollView view;
        List<Button> buttons;
        internal BoxPage(GameInfo gamePage)
        {
            InitializeComponent();
            BindingContext = gameInfo = gamePage;
            game = new Game();
            LoadAsync().Wait();
            database.CreateTable<BoxRecord>();
        }
        async Task LoadAsync()
        {
            var gameArgs = await database.GetFirstOrDefaultAsync<GameArgs>(x => x.GameID == gameInfo.ID).ConfigureAwait(false);
            if(gameArgs != null)
            {
                boxLevel = BaseArgs.Convert<BoxLevel>(gameArgs);
            }
            else
            {
                boxLevel = new BoxLevel()
                {
                    GameID = gameInfo.ID,
                    Version = gameInfo.Version,
                    Level = 0,
                    MaxLevel = 0
                };
            }
            if((boxLevel.Version ?? "0").CompareTo("1.2") < 0)
            {
                database.DropTable<BoxRecord>();
                boxLevel = new BoxLevel()
                {
                    GameID = gameInfo.ID,
                    Version = gameInfo.Version,
                    Level = 0,
                    MaxLevel = 0
                };
                await database.SaveAsync(boxLevel.ToGameArgs());
            }
            if(Utils.NoMaxLimit)
            {
                boxLevel.MaxLevel = map.Maps.Length;
            }
        }
        async Task SaveArgsAsync()
        {
            await database.SaveAsync(boxLevel.ToGameArgs());
        }
        void OnLayoutSizeChanged(object sender, EventArgs args)
        {
            Layout layout = sender as Layout;
            layoutWidth = (int)layout.Width;
            layoutHeight = (int)layout.Height;
            game.Init(map.Maps[boxLevel.Level]);
            InitLayout();
        }

        void InitLayout()
        {
            gameInfo.Level = boxLevel.Level + 1;
            gameInfo.StepCount = 0;
            var sizew = layoutWidth / game.Width;
            var sizeh = layoutHeight / game.Height;
            cellSize = Math.Min(sizew, sizeh);
            xMargin = (layoutWidth - game.Width * cellSize) / 2;
            yMargin = (layoutHeight - game.Height * cellSize) / 2;

            absoluteLayout.Children.Clear();
            var map = game.DeconstructMap();
            foreach(var (x, y, s) in map)
            {
                GameCell lifeCell = new GameCell(-1, s);
                absoluteLayout.Children.Add(lifeCell);
                Rectangle rect = new Rectangle(x * cellSize + xMargin, y * cellSize + yMargin, cellSize, cellSize);
                AbsoluteLayout.SetLayoutBounds(lifeCell, rect);
            }
            index0 = map.Count();
            var list = game.Deconstruct().OrderBy(x => x.Item1);
            foreach(var (id, x, y, s) in list)
            {
                GameCell lifeCell = new GameCell(id, s);
                absoluteLayout.Children.Add(lifeCell);
                Rectangle rect = new Rectangle(x * cellSize + xMargin, y * cellSize + yMargin, cellSize, cellSize);
                AbsoluteLayout.SetLayoutBounds(lifeCell, rect);
                lifeCell.Show();
            }
            TimeCounter.Start();
        }

        async void OnSwiped(object sender, SwipedEventArgs e)
        {
            if(game.IsFinished)
            {
                return;
            }
            if(await game.Move(e.Direction.ToDirection(), Push))
            {
                gameInfo.StepCount++;
            }
            if(game.IsFinished)
            {
                await ShowFinish();
            }
        }

        async void TapGestureRecognizer_Tapped(object sender, EventArgs e)
        {
            if(game.IsFinished || gameInfo.StepCount <= 0)
            {
                return;
            }
            await game.Back(Push);
            gameInfo.StepCount--;
        }

        Task Push(int id, int x, int y, byte s)
        {
            var cell = (GameCell)absoluteLayout.Children[id + index0];
            var fromBound = AbsoluteLayout.GetLayoutBounds(cell);
            var fromx = fromBound.X;
            var fromy = fromBound.Y;
            var tox = x * cellSize + xMargin;
            var toy = y * cellSize + yMargin;
            var taskCompletionSource = new TaskCompletionSource<bool>();

            cell.Animate<Rectangle>(
                "Push",
                t => new Rectangle(fromx + t * (tox - fromx), fromy + t * (toy - fromy), fromBound.Width, fromBound.Height),
                r => AbsoluteLayout.SetLayoutBounds(cell, r),
                16,
                125,
                Easing.Linear,
                (r, b) => { cell.Status = s; taskCompletionSource.SetResult(b); }
            );
            return taskCompletionSource.Task;
        }

        async Task ShowFinish()
        {
            var record = await SaveRecordAsync();
            if(boxLevel.Level >= map.Maps.Length - 1)
            {
                await DisplayAlert(record.Level, record.Message, "OK");
                return;
            }
            var flag = await DisplayAlert(record.Level, $"{record.Message}\r\n\r\n是否进入下一关？", "YES", "NO");
            if(boxLevel.MaxLevel == boxLevel.Level && boxLevel.MaxLevel < map.Maps.Length - 1)
            {
                boxLevel.MaxLevel++;
                if(this.buttons != null)
                {
                    this.buttons[boxLevel.MaxLevel].IsEnabled = true;
                }
            }
            if(flag)
            {
                boxLevel.Level++;
                await SaveArgsAsync();
                game.Init(map.Maps[boxLevel.Level]);
                InitLayout();
            }
        }
        async Task<Record> SaveRecordAsync()
        {
            var dur = TimeCounter.Stop();
            var cRecord = new BoxRecord()
            {
                Step = gameInfo.StepCount,
                GameID = gameInfo.ID,
                CreateTime = DateTime.Now,
                Level = boxLevel.Level + 1,
                Duration = dur,
                MinStep = game.MinStep,
            };
            await database.SaveRecordByLevel<BoxRecord>(cRecord,
                o => o.Level == cRecord.Level,
                o => o.Step > cRecord.Step || (o.Step == cRecord.Step && o.Duration > cRecord.Duration)
            );
            return cRecord.Convert();
        }

        async void LevelClicked(object sender, EventArgs args)
        {
            if(!mask.Contains("levels"))
            {
                (view, buttons) = ControlUtil.GetLevelGrid(map.Maps.Length, boxLevel.MaxLevel, 5, LevelSelect);
                mask.Add("levels", "选择关卡", view);
            }
            mask.ShowWithCancel("levels");
            await view.ScrollToAsync(this.buttons[boxLevel.Level], ScrollToPosition.Center, false);
        }
        async void LevelSelect(int level)
        {
            mask.Hide();
            if(boxLevel.Level != level - 1)
            {
                boxLevel.Level = level - 1;
                await SaveArgsAsync();
            }
            game.Init(map.Maps[boxLevel.Level]);
            InitLayout();
        }

        void RestartClicked(object sender, EventArgs args)
        {
            mask.Hide();
            game.Init(map.Maps[boxLevel.Level]);
            InitLayout();
        }

        void OnAboutButtonClicked(object sender, EventArgs args)
        {
            if(!mask.Contains("about"))
            {
                var aboutView = ControlUtil.GetAbout(gameInfo);
                mask.Add("about", gameInfo.Name, aboutView);
            }
            mask.ShowWithCancel("about", "确定");
        }

        void OnRecordClicked(object sender, EventArgs args)
        {
            mask.Hide();
            Navigation.PushAsync(new RecordPage(gameInfo.Name, new RecordViewModel<BoxRecord>(null)));
        }

        private void TapToBack(object sender, EventArgs e)
        {
            Navigation.PopAsync();
        }
        protected override bool OnBackButtonPressed()
        {
            return true;
        }
    }
}